/**
 * Example: http://keaplogik.blogspot.ca/2012/05/atmosphere-websockets-comet-with-spring.html
 */

package com.sian.atmosphere.controllers;

import java.util.Locale;
import java.util.concurrent.CountDownLatch;

import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sian.atmosphere.services.BroadcasterService;
import com.sian.atmosphere.services.FeedService;
import com.sian.atmosphere.services.PresentService;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	FeedService feedService;
	@Autowired
	BroadcasterService broadcasterService;
	@Autowired
	PresentService presentService;

	private void suspend(final AtmosphereResource resource) {
		final CountDownLatch countDownLatch = new CountDownLatch(1);
		resource.addEventListener(new AtmosphereResourceEventListenerAdapter() {
			@Override
			public void onSuspend(AtmosphereResourceEvent event) {
				countDownLatch.countDown();
				resource.removeEventListener(this);
			}
		});
		resource.suspend();
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! the client locale is " + locale.toString());
		model.addAttribute("serverTime", feedService.formatDate(locale));
		return "home";
	}

	@RequestMapping(value = "/broadcast/subscribe")
	@ResponseBody
	public void messageAsync(AtmosphereResource atmosphereResource) {
		atmosphereResource.addEventListener(new AtmosphereResourceEventListenerAdapter()
		{
			public void onDisconnect(AtmosphereResourceEvent event)
			{
				presentService.remove("UNKNOWN");
			}
		});
		this.suspend(atmosphereResource);
		
		presentService.register("UNKNOWN", atmosphereResource.uuid());

		broadcasterService.subscribeToSystemBroadcaster(atmosphereResource);
		Object missedMessage = atmosphereResource.getAtmosphereResourceEvent().getMessage();
		if(null != missedMessage)
		{
			logger.debug(missedMessage.toString());
			broadcasterService.sendMessageToPeer("UNKNOWN", "UNKNOWN", missedMessage);
		}
	}
}
